package com.songxh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.songxh.common.R;
import com.songxh.pojo.Employee;
import com.songxh.service.EmployeeService;
import com.songxh.service.impl.EmployeeServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * @author songxh
 * @create 2022-04-22-11:23
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;


    /**
     * 登录
     * @param request  用于session存用户消息
     * @param employee  前台会穿进来一个username和password，是json格式，需要 @RequestBody注解
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(
            HttpServletRequest request,
            @RequestBody
            Employee employee
    ){

        //将页面提交的密码使用md5加密
        String password = employee.getPassword();
        password= DigestUtils.md5DigestAsHex(password.getBytes());

        //根据页面提交的username来查修用户
        String username = employee.getUsername();
        QueryWrapper<Employee> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        Employee employeeServiceOne = employeeService.getOne(queryWrapper);

        //如果没有查询到则返回登录失败结果
        if (employeeServiceOne==null){
            return R.error("该用户不存在，请重新登录");
        }

        //校验密码，如果不一致就返回登陆失败
        if (!employeeServiceOne.getPassword().equals(password)){
            return R.error("密码错误，登录失败");
        }

        //查看员工状态，若已经被封禁，则返回被封禁
        if (employeeServiceOne.getStatus()==0){
            return R.error("该用户已被封禁，不能登录");
        }

        //登录成功，将用户id存进session，并返回登录成功
        HttpSession session = request.getSession();
        session.setAttribute("employee",employeeServiceOne.getId());
        return R.success(employeeServiceOne);
    }


    /**
     * 退出登录
     * @param request  用于清除session的内容
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("employee");
        return R.success("退出成功");
    }


    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        log.info("新增员工信息为：{}",employee.toString());

        //设置初始密码为123456，使用md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //这些内容全在MyMetaObjectHandler中自动填充
        //设置创建时间和修改时间
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //获取当前登录的用户的id
        //Long id = (Long) request.getSession().getAttribute("employee");
        //设置创建的id和修改的id
        //employee.setCreateUser(id);
        //employee.setUpdateUser(id);

        //添加,该sabe方法有mybatisplus提共
        employeeService.save(employee);

        return R.success("新增员工成功");
    }


    /**
     * 员工分页查询
     * @param page  页码
     * @param pageSize  每页的页数
     * @param name  搜索框搜索的名字
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        Page pageInfo=new Page(page,pageSize);

        QueryWrapper<Employee> queryWrapper=new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)){
            queryWrapper.like("name", name);
        }
        queryWrapper.orderByDesc("update_time"); //根据修改时间从大到小排序
        employeeService.page(pageInfo,queryWrapper);

        return R.success(pageInfo);
    }


    /**
     * 修改员工信息
     * @param employee  前台传过来的员工信息
     * @param request
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpServletRequest request){

        //Long empId = (Long) request.getSession().getAttribute("employee");
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(empId);
        employeeService.updateById(employee);

        return R.success("修改成功");
    }


    /**
     * 根据id查询员工  用于修改数据时的回显功能
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable long id){
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }


}
